package com.ushier.shop.fruits.dao;

import com.ushier.shop.fruits.bean.User;
import com.ushier.shop.fruits.db.DBHelper;
import com.ushier.shop.fruits.util.BeanUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDAO {

    private DBHelper helper = new DBHelper();

    public User get(String name){

        String sql = "SELECT id, name, password FROM _user WHERE name = ?";

        List<Map<String, Object>> list = helper.query(sql, new String[]{name});
        if(null == list || list.isEmpty()){
            return null;
        }

        Map<String, Object> map = list.get(0);
        User user = BeanUtil.mapToObject(map, User.class);
        return user;
    }

    public boolean insert(String name, String password){

        User user = this.get(name);
        if(null != user){
            return false;
        }

        String sql = "INSERT INTO _user (name, password) VALUES(?, ?)";
        int update = helper.update(sql, new String[]{name, password});
        return update > 0;
    }

    public List<User> list(){
        String sql = "SELECT id, name FROM _user";
        List<Map<String, Object>> list = helper.query(sql);
        if(null == list || list.isEmpty()){
            return null;
        }

        List<User> retList = new ArrayList<>();
        list.forEach(map -> {
            retList.add(BeanUtil.mapToObject(map, User.class));
        });

        return retList;
    }

}
